package net.forsalemall.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.github.droidfu.widgets.WebImageView;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.Utils;

public class CategoriesActivity extends ListActivity {

	private List<ListItem> items;
	private EfficientAdapter adap;
	private String categoryData;
	private JSONArray jCategories;
	
	private Action showAllAds;

	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			setContentView(R.layout.category);
			final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
			actionBar.setTitle(getIntent().getStringExtra(
					Constants.KEY_SUPER_CATEGORY_NAME));
			actionBar.setHomeAction(new Action() {

				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});
			showAllAds = new Action() {
				public void performAction(View view) {
					showAllAds();
				}

				public int getDrawable() {
					return R.drawable.ic_menu_sup_cat;
				}
			};
			
			actionBar.setDisplayHomeAsUpEnabled(true);
			actionBar.addAction(showAllAds);
			items = new ArrayList<ListItem>();
			categoryData = getIntent().getStringExtra(
					Constants.KEY_SUPER_CATEGORY_DATA);

			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;

				protected void onPreExecute() {
					try {
						progressDialog = Utils.getProgressDialog(
								CategoriesActivity.this, null,
								getString(R.string.loading));
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						// categoryData = HttpUtils.getForsaleCategoriesData();
						jCategories = new JSONArray(categoryData);
						if (jCategories != null) {
							JSONObject jo;
							String fileName;
							for (int i = 0; i < jCategories.length(); i++) {
								jo = jCategories.getJSONObject(i);

								fileName = jo.getString("img_file_name");
								if (fileName != null && fileName.length() > 3) {
									items.add(new ListItem(jo.getInt("cat_id"),
											jo.getInt("ad_count"),
											Utils.getDecodedString(jo
													.getString("cat_name")),
											HttpUtils.getFileUrl(Constants
													.getCatImgThumbDirName(),
													fileName)));
								} else {
									items.add(new ListItem(
											jo.getInt("cat_id"),
											jo.getInt("ad_count"),
											Utils.getDecodedString(jo
													.getString("cat_name")),
											HttpUtils.getFileUrl(
													Constants
															.getDefaultImgDirName(),
													Constants
															.getDefaultImgFileName())));
								}

							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						adap = new EfficientAdapter(CategoriesActivity.this);
						setListAdapter(adap);
						progressDialog.dismiss();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void showAllAds(){
		try {
			Intent intent = new Intent(this, AdsBySupCatActivity.class);
			intent.putExtra(Constants.KEY_COUNTRY_CODE, getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE));
			intent.putExtra(Constants.KEY_SUPER_CATEGORY_ID,
					getIntent().getIntExtra(Constants.KEY_SUPER_CATEGORY_ID, 0));
			intent.putExtra(Constants.KEY_SUPER_CATEGORY_NAME,
					getIntent().getStringExtra(Constants.KEY_SUPER_CATEGORY_NAME));
			intent.putExtra(
					Constants.KEY_AD_TYPE,
					getIntent().getIntExtra(Constants.KEY_AD_TYPE,
							Constants.TYPE_NORMAL_AD));
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		try {
			Intent intent = new Intent(this, AdsByCategoryActivity.class);
			intent.putExtra(Constants.KEY_COUNTRY_CODE, getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE));
			intent.putExtra(Constants.KEY_CATEGORY_ID,
					items.get(position).cat_id);
			intent.putExtra(Constants.KEY_CATEGORY_NAME,
					items.get(position).title);
			intent.putExtra(
					Constants.KEY_AD_TYPE,
					getIntent().getIntExtra(Constants.KEY_AD_TYPE,
							Constants.TYPE_NORMAL_AD));
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class ListItem {
		private int cat_id;
		private int count;
		private String title;
		private String url;

		public ListItem(int cat_id,int count, String title, String url) {
			this.cat_id = cat_id;
			this.count = count;
			this.title = title;
			this.url = url;
		}

		public int getCatId() {
			return cat_id;
		}

		public String getTitle() {
			return title;
		}

		public String getUrl() {
			return url;
		}

	}

	public class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Context context;

		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.category_list_content,
						null);
				holder = new ViewHolder();
				holder.icon = (WebImageView) convertView
						.findViewById(R.id.list_icon);
				holder.title = (TextView) convertView
						.findViewById(R.id.list_title);
				holder.countView = (TextView) convertView
				.findViewById(R.id.list_count_view);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position % 2 == 0) {
				convertView.setBackgroundColor(Constants.BG_EVEN_CELL);
			} else {
				convertView.setBackgroundColor(Constants.BG_ODD_CELL);
			}
			holder.icon.setImageUrl(items.get(position).url);
			holder.icon.loadImage();
			holder.title.setText(items.get(position).title);
			holder.countView.setText(Integer.toString(items.get(position).count));
			return convertView;
		}

		class ViewHolder {
			WebImageView icon;
			TextView title;
			TextView countView;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}
	}
}